package com.tuhui.quartz;

import com.tuhui.service.AckSenderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling
@Slf4j
public class ScheduledTasks {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Autowired
    private AckSenderService ackSenderService;

    @Value("${file.path}")
    private String filePath;
    //每1分钟执行一次
    @Scheduled(cron = "0 */1 *  * * * ")
    public void reportCurrentByCron(){
          log.info("执行定时任务开始");
          ackSenderService.send();
          log.info("执行定时任务结束");
    }

    //每2分钟执行一次
    //@Scheduled(cron = "0 */2 *  * * * ")
    public void deletFile(){
        log.info("执行删除文件定时任务开始");
        ackSenderService.deleteFile();
        log.info("执行删除文件任务结束");
    }

    private SimpleDateFormat dateFormat(){
        return new SimpleDateFormat ("HH:mm:ss");
    }

    public void sendFile(File file){
        rabbitTemplate.convertAndSend("hello",file);
    }


    public ArrayList<File> getFiles(String path) throws Exception {
        //目标集合fileList
        ArrayList<File> fileList = new ArrayList<File>();
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileIndex : files) {
                //如果这个文件是目录，则进行递归搜索
                if (fileIndex.isDirectory()) {
                    getFiles(fileIndex.getPath());
                } else {
                    //如果文件是普通文件，则将文件句柄放入集合中
                    fileList.add(fileIndex);
                }
            }
        }
        return fileList;
    }
}
